package com.xiaoyuzhou.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetUtils {
	
	public static String getResponseData(String requestData) {
		System.out.println("requestData: " + requestData);
		String responseData = "";
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response;
		try {
			response = httpClient.execute(new HttpGet(requestData));
			HttpEntity entity = response.getEntity();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(entity.getContent()));
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				responseData = responseData + line;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		System.out.println("responseData: "+ responseData);
		return responseData;
	}

	public static InputStream getInputStream(String url) {
		System.out.println("url: " + url);
		try {
			URL _url = new URL(url);
			HttpURLConnection http = (HttpURLConnection) _url.openConnection();
			InputStream is = http.getInputStream();
			return is;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 检查网络是否连接
	 * @param context
	 * @return
	 */
	public static boolean checkNet(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
}
